﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpObjects.SearchEngine.HtmlParsing.Html
{
    public class HtmlTableTag : HtmlContainerTag
    {
        public const string TagName = "table";

        public override string Name { get { return TagName; } set { } }

        public HtmlTableTag(HtmlGenericTag tag = null)
            : base(tag)
        {
        }

        public override bool IsContent { get { return true; } set { } }

        public HtmlTableCaptionTag Caption
        {
            get
            {
                var caption =
                    (from tableCaption in this.Children
                     where tableCaption is HtmlTableCaptionTag
                     select tableCaption).FirstOrDefault();

                if(caption == null)
                {
                    return new HtmlTableCaptionTag() {Name = "caption", Text = string.Empty};
                }
                else
                {
                    return (HtmlTableCaptionTag)caption;
                }
            }
        }

        public List<HtmlTableHeaderTag> Headers
        {
            get
            {
                var headers =
                    from tableHeader in this.Children
                    where tableHeader is HtmlTableHeaderTag
                    select tableHeader;

                List<HtmlTableHeaderTag> headerList = new List<HtmlTableHeaderTag>();
                
                foreach (HtmlTableHeaderTag header in headers)
                {
                    headerList.Add(header);
                }

                return headerList;
            }
        }
        
        public List<HtmlTableCellTag> Cells
        {
            get
            {
                var cells =
                    from tableCell in this.Children
                    where tableCell is HtmlTableCellTag
                    select tableCell;

                List<HtmlTableCellTag> cellList = new List<HtmlTableCellTag>();
                
                foreach (HtmlTableCellTag cell in cells)
                {
                    cellList.Add(cell);
                }

                return cellList;
            }
        }

        public static HtmlTag CreateInstance(HtmlGenericTag tag)
        {
            return new HtmlTableTag(tag);
        }
    }
}
